package com.qinggeng.project.system.controller;

import com.qinggeng.common.enums.CommonEnum;
import com.qinggeng.common.enums.UserTypeEnum;
import com.qinggeng.common.utils.SecurityUtils;
import com.qinggeng.framework.web.domain.AjaxResult;
import com.qinggeng.project.system.domain.Goods;
import com.qinggeng.project.system.dto.SpecialGoods;
import com.qinggeng.project.system.service.IGoodsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/specialGoods")
public class SpecialGoodsController {
    @Autowired
    private IGoodsService goodsService;

    @PostMapping("/add")
    public AjaxResult add(SpecialGoods specialGoods){
        Goods goods = new Goods();
        BeanUtils.copyProperties(specialGoods,goods);
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())){
            goods.setShopId(SecurityUtils.getShopId());
            goods.setAddType(CommonEnum.STATUS_20.getValue());
        }
        Long mainCategory =  goodsService.selectMaxGoodsId();

        if (mainCategory == null){

            mainCategory = 1L;
        }else {
            mainCategory +=1;
        }

        goods.setMainCategory(mainCategory);
        return AjaxResult.success(goodsService.insertGoods(goods));
    }

    @PutMapping("/add")
    public AjaxResult edit(SpecialGoods specialGoods){
        Goods goods = new Goods();
        BeanUtils.copyProperties(specialGoods,goods);
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())){
            Goods goods1 = goodsService.selectGoodsById(goods.getGoodsId());
            if (goods1.getShopId() == null || !goods1.getShopId().equals(SecurityUtils.getShopId())){
                return AjaxResult.error("只能操作自己所属商品");
            }
        }
        return AjaxResult.success(goodsService.updateGoods(goods));
    }
}
